const express = require("express");
// const bodyParser = require("body-parser"); /* deprecated */
const cors = require("cors");

// const CryptoJS=require("crypto-js")



const bodyParser = require("body-parser");
const multer = require('multer');
const path = require("path");

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.text());

var corsOptions = {
  origin: "http://localhost:8081"
};



// 设置source_map为静态资源的访问路径，满足//# sourceMappingURL=http://localhost:8080/IAM555/js/app.2a708beb.js.map可以被直接访问到
app.use(express.static(__dirname+ '/source_map'));

require("./app/routes/sourcemap.routes.js")(app);


// curl -i -X POST -H "Content-Type: multipart/form-data" -F "file=@/Users/longfusun/vue/everbrightgame/application/dist/IAM555/js/about.03b3bdc2.js.map" -F "param1=value1" http://localhost:8080/upload

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json()); /* bodyParser.json() is deprecated */

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true })); /* bodyParser.urlencoded() is deprecated */

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome, cmsServer lunched." });
});


require("./app/routes/demoError.routes.js")(app);
require("./app/routes/tutorial.routes.js")(app);
require("./app/routes/error.routes.js")(app);

const clientList = [];
const expressWs = require('express-ws')(app)
expressWs.getWss().on('connection', function(ws, req) {
  ws.customerId = req.query.userID;
  clientList.push(ws)
});

// const websocket = require('./app/websocket')
app.ws('/websocket/test', function(ws, req) {
  ws.on('message', function(msg) {
    const {payload, fromId} = JSON.parse(msg)
    clientList.forEach(client=>{
      if (fromId=== "773914" && client.customerId === "775773") {
        client.send(payload)
      } else if (fromId=== "775773" && client.customerId === "773914") {
        client.send(payload)
      }
    })
    console.log(msg);
  });
});

// app.use("/api/error/report", (req, res) => {
//   const logs = typeof req.body === 'object' ? req.body : JSON.parse(req.body);

//   console.log(JSON.parse(JSON.parse(req.body)[0]));
//   // logs.forEach(async item => {
//   //   const log = JSON.parse(item);
//   //   const { appId, userId, type, data, currentTime, currentPage, ua } = log; 
//   //   console.log("item", log)
//   // })
//   res.send("发送成功");
// });




// set port, listen for requests
const PORT = 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
